package nccloud.arap.servlet;

import com.alibaba.fastjson.JSONObject;
import com.yonyou.cloud.utils.CollectionUtils;
import com.yonyou.cloud.utils.StringUtils;
import nc.bs.dao.BaseDAO;
import nc.bs.framework.adaptor.IHttpServletAdaptor;
import nc.bs.framework.common.InvocationInfoProxy;
import nc.bs.framework.common.NCLocator;
import nc.bs.framework.server.ISecurityTokenCallback;
import nc.jdbc.framework.processor.ColumnListProcessor;
import nc.vo.pub.BusinessException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;

public class ArapF3Bill extends HttpServlet implements IHttpServletAdaptor {

    private BaseDAO baseDAO = null;

    private BaseDAO getBaseDAO() throws Exception
    {
        if (baseDAO == null)
        {
            baseDAO = new BaseDAO();
        }
        return baseDAO;
    }

    @Override
    public void doAction(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        request.setCharacterEncoding("UTF-8");/** 设置请求编码 */
        response.setContentType("text/html");/** 设置响应类型 */
        response.setCharacterEncoding("UTF-8");/** 设置响应编码 */

        JSONObject resp = new JSONObject();

        try {
            loginNcSystem();// 模拟登录
            String dataSource = request.getParameter("datasource");// 指定数据源
            if (StringUtils.isBlank(dataSource)) {
                throw new ServletException("datasource参数不能为空");
            }
            InvocationInfoProxy.getInstance().setUserDataSource(dataSource);
            InvocationInfoProxy.getInstance().setGroupId("0001A210000000000JB9");

            // 接口数据
            String requestStr = readRequest(request);
            JSONObject req =  JSONObject.parseObject(requestStr);

            /**
             * 合同处理
             */
            String action = req.getString("action");
            if("QUERY".equals(action)){
                doQuery(req, resp);
            }else{
                resp.put("issuccess", "N");
                resp.put("msg", "无法识别传输的接口动作");
            }
        } catch (Exception e) {
            resp.put("issuccess", "N");
            resp.put("msg", e.getMessage());
        }

        response.getWriter().print(resp);
    }


    /**
     * 保存合同
     * @return
     * @throws BusinessException
     */
    public void doQuery(JSONObject req, JSONObject resp) throws Exception
    {
        JSONObject apVO = req.getJSONObject("apVO");
        String vbillcode = apVO.getString("vbillcode");
        String sql = "SELECT billno,billdate,pk_org,pk_deptid,pu_org,pu_deptid,pu_psndoc,local_money_de FROM ap_payitem WHERE contractno ='" + vbillcode + "' and NVL(dr,0) = 0 ";
        List<String> payBillList = (List) this.getBaseDAO().executeQuery(sql, new ColumnListProcessor());
        if (CollectionUtils.isNotEmpty(payBillList)){
            resp.put("issuccess", "N");
            resp.put("msg", "未查询到["+vbillcode+"]相关付款单信息");
        }else{
            resp.put("issuccess", "Y");
            resp.put("msg", "存在["+vbillcode+"]合同相关付款单信息");
        }
    }




    /**
     * 从request中获取接口数据
     * @param request 接口请求
     * */
    private String readRequest(HttpServletRequest request) throws Exception {
        InputStreamReader insr = new InputStreamReader(request.getInputStream(), "utf-8");
        StringBuffer result = new StringBuffer();
        int respInt = insr.read();
        while (respInt != -1) {
            result.append((char) respInt);
            respInt = insr.read();
        }
        if (result.length() < 1) {
            throw new BusinessException("未获取到请求体信息，请检查！");
        }
        return result.toString();
    }

    /**
     * 登录nc系统
     */
    private void loginNcSystem() {
        NCLocator.getInstance().lookup(ISecurityTokenCallback.class)
                .token("NCSystem".getBytes(), "pfxx".getBytes());
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        doAction(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        doAction(req, resp);
    }

}
